<template>
  <div class="users-page">
    <div class="page-header">
      <h1>User Management</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        Add User
      </el-button>
    </div>
    
    <el-card>
      <div class="table-toolbar">
        <el-input
          v-model="searchText"
          placeholder="Search users..."
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredUsers"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="username" label="Username" sortable />
        <el-table-column prop="email" label="Email" sortable />
        <el-table-column prop="fullName" label="Full Name" />
        <el-table-column label="Roles">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              size="small"
              style="margin-right: 5px"
            >
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Created" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editUser(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit User Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingUser ? 'Edit User' : 'Create User'"
      width="600px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="Username" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        
        <el-form-item label="Email" prop="email">
          <el-input v-model="userForm.email" type="email" />
        </el-form-item>
        
        <el-form-item v-if="!editingUser" label="Password" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        
        <el-form-item label="Full Name">
          <el-input v-model="userForm.fullName" />
        </el-form-item>
        
        <el-form-item label="Phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        
        <el-form-item label="Roles" prop="roleIds">
          <el-select
            v-model="userForm.roleIds"
            multiple
            placeholder="Select roles"
            style="width: 100%"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="editingUser" label="Status">
          <el-switch
            v-model="userForm.isActive"
            active-text="Active"
            inactive-text="Inactive"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelEdit">Cancel</el-button>
        <el-button type="primary" :loading="saving" @click="saveUser">
          {{ editingUser ? 'Update' : 'Create' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import api from '@/api'

interface User {
  id: number
  username: string
  email: string
  fullName?: string
  phone?: string
  isActive: boolean
  createdAt: string
  roles: Role[]
}

interface Role {
  id: number
  name: string
  description?: string
  isActive: boolean
  createdAt: string
}

const users = ref<User[]>([])
const roles = ref<Role[]>([])
const loading = ref(false)
const saving = ref(false)
const searchText = ref('')
const showCreateDialog = ref(false)
const editingUser = ref<User | null>(null)
const userFormRef = ref<FormInstance>()

const userForm = reactive({
  username: '',
  email: '',
  password: '',
  fullName: '',
  phone: '',
  roleIds: [] as number[],
  isActive: true
})

const userRules: FormRules = {
  username: [
    { required: true, message: 'Please input username', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input valid email', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' },
    { min: 6, message: 'Password must be at least 6 characters', trigger: 'blur' }
  ]
}

const filteredUsers = computed(() => {
  if (!searchText.value) return users.value
  return users.value.filter(user =>
    user.username.toLowerCase().includes(searchText.value.toLowerCase()) ||
    user.email.toLowerCase().includes(searchText.value.toLowerCase()) ||
    user.fullName?.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

const loadUsers = async () => {
  loading.value = true
  try {
    const response = await api.get('/users')
    users.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load users')
  } finally {
    loading.value = false
  }
}

const loadRoles = async () => {
  try {
    const response = await api.get('/roles')
    roles.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load roles')
  }
}

const handleSearch = () => {
  // Search is handled by computed property
}

const handleSortChange = ({ prop, order }: any) => {
  // Implement sorting logic if needed
}

const editUser = (user: User) => {
  editingUser.value = user
  userForm.username = user.username
  userForm.email = user.email
  userForm.fullName = user.fullName || ''
  userForm.phone = user.phone || ''
  userForm.roleIds = user.roles.map(role => role.id)
  userForm.isActive = user.isActive
  userForm.password = ''
  showCreateDialog.value = true
}

const deleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete user "${user.username}"?`,
      'Confirm Delete',
      {
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    
    await api.delete(`/users/${user.id}`)
    ElMessage.success('User deleted successfully')
    loadUsers()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete user')
    }
  }
}

const saveUser = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingUser.value) {
          await api.put(`/users/${editingUser.value.id}`, {
            username: userForm.username,
            email: userForm.email,
            fullName: userForm.fullName,
            phone: userForm.phone,
            roleIds: userForm.roleIds,
            isActive: userForm.isActive
          })
          ElMessage.success('User updated successfully')
        } else {
          await api.post('/users', userForm)
          ElMessage.success('User created successfully')
        }
        
        showCreateDialog.value = false
        loadUsers()
        resetForm()
      } catch (error) {
        ElMessage.error(editingUser.value ? 'Failed to update user' : 'Failed to create user')
      } finally {
        saving.value = false
      }
    }
  })
}

const cancelEdit = () => {
  showCreateDialog.value = false
  resetForm()
}

const resetForm = () => {
  editingUser.value = null
  Object.assign(userForm, {
    username: '',
    email: '',
    password: '',
    fullName: '',
    phone: '',
    roleIds: [],
    isActive: true
  })
  userFormRef.value?.resetFields()
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

onMounted(() => {
  loadUsers()
  loadRoles()
})
</script>

<style scoped>
.users-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.table-toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
